<?php namespace App\Controllers\Manager;

//http://www.codeforest.net/laravel4-simple-website-with-backend-1
 
use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\ProductAttribute;
use App\Models\ProductImage;
use App\Models\ProductImageType;
use App\Models\ProductFile;
use App\Models\ProductFileType;
use Input, Redirect, Sentry, Str, Response, Config;
use Notification;
 
class ProductsController extends \BaseController {
 
    public function index()
    {
        return \View::make('manager.products.index')
            ->with('products', Product::all());
    }
 
    public function show($id)
    {
        /*return \View::make('manager.pages.show')
            ->with('page', Page::find($id));*/
    }
 
    public function create()
    {
        $product_categories = array();
        foreach(ProductCategory::all() as $product_category)
        {
            $product_categories[$product_category->id] = $product_category->title;
        }
		
        $product_attributes = array();
        foreach(ProductAttribute::all() as $product_attribute)
        {
            $product_attributes[$product_attribute->id] = $product_attribute->attributename;
        }

        return \View::make('manager.products.create')
            ->with('product_attributes', $product_attributes)
			->with('product_categories', $this->getCategoryList(0, array()));
    }
 
    public function store()
    {
        $product = new Product;
        $product->categoryid   = Input::get('productcategoryid',0);
        $product->name   = Input::get('name');
        $product->slug    = Str::slug(Input::get('slug'));
        $product->shortdescription   = Input::get('shortdescription');
        $product->description   = Input::get('description');
        $product->status = Input::get('status');
        $product->save();
        
        $product->categories()->sync(Input::get("categoryid", array()));
		
		if(Input::get("numattributes") > 0)
		{
			for($i=1; $i <= Input::get("numattributes"); $i++)
			{
				if(Input::get("attribute".$i) >= 0)
				{
					$pa = ProductAttribute::find(Input::get("attribute".$i));
				}
				else
				{
					$pa = new ProductAttribute;
					$pa->attributename = Input::get("attributename".$i);
					$pa->save();	
				}
				
				
				$product->attributes()->attach(
					$pa->id, array('content' => Input::get("content".$i))
				);
			}
		}
		
        Notification::success('The product was saved.');
     
        return Redirect::route('manager.products.index');
    }
 
    public function edit($id)
    {
        $product_categories = array();
        foreach(ProductCategory::all() as $product_category)
        {
            $product_categories[$product_category->id] = $product_category->title;
        }
		
		$product_attributes = array();
        foreach(ProductAttribute::all() as $product_attribute)
        {
            $product_attributes[$product_attribute->id] = $product_attribute->attributename;
        }
		
		$product_imagetypes = array();
        foreach(ProductImageType::all() as $product_imagetype)
        {
            $product_imagetypes[$product_imagetype->id] = $product_imagetype->type;
        }

		$product_filetypes = array();
        foreach(ProductFileType::all() as $product_filetype)
        {
            $product_filetypes[$product_filetype->id] = $product_filetype->type;
        }
		
		$product = Product::find($id);
		$vals = array();
		foreach($product->categories()->get(array("id")) as $key => $val)
		{
			$vals[] = $val["id"];
		}

        return \View::make('manager.products.edit')
            ->with('product', $product)
            ->with('unrelatedproducts', $product->unrelatedproducts()->get())
            ->with('relatedproducts', $product->relatedproducts()->get())
            ->with('product_categories', $this->getCategoryList(0, $vals))
			->with('product_attributes', $product_attributes)
			->with('product_imagetypes', $product_imagetypes)
			->with('product_filetypes', $product_filetypes);
    }
 
    public function update($id)
    {
        $product = Product::find($id);
        $product->categoryid   = Input::get('productcategoryid',0);
        $product->name   = Input::get('name');
        $product->slug    = Str::slug(Input::get('slug'));
        $product->shortdescription   = Input::get('shortdescription');
        $product->description   = Input::get('description');
        $product->status = Input::get('status');
        $cats = array();
        if(count(Input::get("categoryid")) > 0)
        {
            $cats = Input::get("categoryid");
        }
        $product->categories()->sync($cats);
        $product->save();
		
		$product->attributes()->detach();
		
		if(Input::get("numattributes") > 0)
		{
			for($i=1; $i <= Input::get("numattributes"); $i++)
			{
				if(Input::get("attribute".$i) >= 0)
				{
					$pa = ProductAttribute::find(Input::get("attribute".$i));
				}
				else
				{
					$pa = new ProductAttribute;
					$pa->attributename = Input::get("attributename".$i);
					$pa->save();	
				}
				
				
				$product->attributes()->attach(
					$pa->id, array('content' => Input::get("content".$i))
				);
			}
		}

        Notification::success('The product was saved.');
     
        return Redirect::route('manager.products.edit', $product->id);
    }
 
    public function destroy($id)
    {
        $product = Product::find($id);
        $product->delete();

        Notification::info('The product was deleted.');

        return Redirect::route('manager.products.index');
    }

    public function getSlug()
    {
        return Response::json(array(
            "val" => Str::slug(Input::get("str"))
        ));
    }
	
	public function uploadImage($id)
	{
		$product = Product::find($id);
		
		if (Input::hasFile('theimage'))
		{
			$destinationPath = Config::get('app.productimagepath').$id;
			$path_parts = pathinfo(Input::file('theimage')->getClientOriginalName());
			
			$newfilename = Str::slug($path_parts["filename"]).".".$path_parts["extension"];
			
			if(!file_exists($destinationPath."/".$newfilename))
			{
				Input::file('theimage')->move($destinationPath, $newfilename);
			
				$pi = new ProductImage;
				$pi->imagefilename = $newfilename;
				$pi->typeid = Input::get('imagetypeid');
				$pi->save();
				
				$product->images()->attach($pi->id);
			}
			
			return Response::json(array(
				"error" => 0 //Str::slug(Input::get("str"))
			));
		}
		else
		{
			return Response::json(array(
				"error" => "No image specified" //Str::slug(Input::get("str"))
			));
		}
	}
	
	public function getImages($productid)
	{
		return \View::make('manager.products.images')
            ->with('product', Product::find($productid));
	}
	
	public function deleteImage($productid, $imageid)
	{
		$product = Product::find($productid);
		$image = ProductImage::find($imageid);
		
		$product->images()->detach($image->id);
		if(file_exists(Config::get('app.productimagepath').$productid."/".$image->imagefilename))
		{
			unlink(Config::get('app.productimagepath').$productid."/".$image->imagefilename);
		}
		$image->delete();
	}
	
	public function uploadFile($id)
	{
		$product = Product::find($id);
		
		if (Input::hasFile('thefile'))
		{
			$destinationPath = Config::get('app.productfilepath').$id;
			$path_parts = pathinfo(Input::file('thefile')->getClientOriginalName());
			
			$newfilename = Str::slug($path_parts["filename"]).".".$path_parts["extension"];
			
			if(!file_exists($destinationPath."/".$newfilename))
			{
				Input::file('thefile')->move($destinationPath, $newfilename);
			
				$pf = new ProductFile;
				$pf->filename = $newfilename;
				$pf->typeid = Input::get('filetypeid');
				$pf->save();
				
				$product->files()->attach($pf->id);
			}
			
			return Response::json(array(
				"error" => 0 //Str::slug(Input::get("str"))
			));
		}
		else
		{
			return Response::json(array(
				"error" => "No file specified" //Str::slug(Input::get("str"))
			));
		}
	}
	
	public function getFiles($productid)
	{
		return \View::make('manager.products.files')
            ->with('product', Product::find($productid));
	}
	
	public function deleteFile($productid, $fileid)
	{
		$product = Product::find($productid);
		$file = ProductFile::find($fileid);
		
		$product->files()->detach($file->id);
		if(file_exists(Config::get('app.productfilepath').$productid."/".$file->filename))
		{
			unlink(Config::get('app.productfilepath').$productid."/".$file->filename);
		}
		$file->delete();
	}
	
	// Utility Functions
    public function getCategoryList($parentid=0, $vals, $class="blocklist", $id="categorylist")
    {
        $html = "<ul class='$class' id='$id-$parentid'>";

        $subs = ProductCategory::where("parentid", $parentid)->get();

        foreach ($subs as $child) {
            $current_id = $child->id;
            $html .= "<li data-pageid='$current_id'><div class='blocklistitem categorylistitem ".((in_array($child->id, $vals))?"selected":"")."'>";
            $html .= "{$child->title}";
            $html .= "<input type='checkbox' name='categoryid[]' class='pull-right' value='{$child->id}' ".((in_array($child->id, $vals))?"checked='checked'":'').">";
			$html .= "</div>";
            
            if(ProductCategory::where("parentid", $current_id)->count() > 0)
            {
                $html .= $this->getCategoryList($current_id, $vals, $class, $id);
            }
            
            $html .= "</li>";
        }
        $html .= "</ul>";
        return $html;
    }
	
	public function saveRelatedProducts()
    {
        $productid = Input::get("productid", 0);
        $relatedproducts = Input::get("relatedproducts", array());

        if(count($relatedproducts) > 0)
        {
            $product = Product::find($productid);
			$product->relatedproducts()->detach();
			
			$syncdata = array();
			foreach($relatedproducts as $order=>$relatedproduct)
            {
                $syncdata[$relatedproduct] = array("displayorder"=>$order + 1);
            }
			$product->relatedproducts()->sync($syncdata);
        }
        
        return \Response::json(array("message" => "Saved!", "productid" => $productid, "relatedproducts" => $relatedproducts));
    }
}